import os
import re
import pandas as pd
import numpy as np
import sys

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(project_root)
from App.AirPhys import calculate_humidity_ratio
from App.read_data import get_flow_report
SCRIPT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
BASE_DIR = os.path.join(SCRIPT_DIR, "System_of_C")
DATA_DIR = os.path.join(BASE_DIR, "read_and_process_data")
OUTPUT_DIR = os.path.join(DATA_DIR, "Load_and_devicedata")
# 确保输出目录存在
os.makedirs(OUTPUT_DIR, exist_ok=True)



# 计算大系统的负荷
def calculate_load(start_time,end_time):
    # 从数据库获取负荷预测用的数据


    '''
    id = 28
    rename_map = {
        "t_LD_in (℃)": "t_LD_in",# 冷冻水回水温度
        "t_LD_out (℃)": "t_LD_out",# 冷冻水出水温度
        "t_w (℃)": "t_w", # 环境温度
        "d_w (%)": "d_w",# 环境湿度
        "Q1-流量": "flow_LD", # 冷冻水流量
        "oriTs":"timestamp"
    }
    data = get_flow_report(id=id, start_time=start_time, end_time=end_time, rename_map=rename_map)

    # data.to_csv(f'{OUTPUT_DIR}/看看数据.csv')

    # 假设大气压为常数
    P = 1013.25
    
    humidity_cols = [col for col in data.columns if "湿度" in col]
    for hum_col in humidity_cols:
        # 匹配"xxx湿度"前缀
        prefix_match = re.match(r"(.*)湿度", hum_col)
        if prefix_match:
            prefix = prefix_match.group(1)
            # 查找对应的温度列（优先找"温度"且带前缀的）
            temp_col_candidates = [col for col in data.columns if prefix in col and "温度" in col]
            if temp_col_candidates:
                temp_col = temp_col_candidates[0]
                T = data[temp_col]
                RH = data[hum_col]
                # 计算饱和水汽压
                Pws = 6.112 * np.exp(17.67 * T / (T + 243.5))
                Pw = Pws * RH / 100
                W = 0.622 * Pw / (P - Pw)
                # 新增一列，命名为"xxx含湿量"
                new_col = prefix + "含湿量"
                data[new_col] = W
    
        # 将包含"温度"列进行合并取平均值，将"湿度"列进行合并取平均值
    col_temperature = [col for col in data.columns if "温度" in col]

    # 计算平均值
    data["t_avg"] = data[col_temperature].mean(axis=1)
    col_humidity = [col for col in data.columns if "含湿量" in col]
    data["humidity_avg"] = data[col_humidity].mean(axis=1)
    # 计算环境含湿量
    T = data["t_w"]
    RH = data["d_w"]
    # 计算饱和水汽压
    Pws = 6.112 * np.exp(17.67 * T / (T + 243.5))
    # 计算环境水汽压
    Pw = Pws * RH / 100
    W = 0.622 * Pw / (P - Pw)
    data["humidity_w"] = W
    '''
    # 计算实际负荷
    # region 老版参数
    id = 32
    rename_map = {
         "冷冻总管热量表-回水温度": "t_LD_in",  # 冷冻水回水温度
         "冷冻总管热量表-供水温度": "t_LD_out",  # 冷冻水出水温度
         "冷源-室外温度": "t_w",  # 环境温度
         "冷源-室外湿度": "d_w",  # 环境湿度
         "冷冻总管热量表-瞬时流量": "flow_LD",  # 冷冻水流量
         "冷冻总管热量表-总冷热量": "real_load",  # 冷冻水流量
         "时间": "timestamp"
    }
    # endregion

    # region 新版参数
    '''
    id = 1  # 新版id
    rename_map = {
        "冷冻总管热量表-回水温度": "t_LD_in",  # 冷冻水回水温度
        "冷冻总管热量表-供水温度": "t_LD_out",  # 冷冻水出水温度
        "冷源-室外温度": "t_w",  # 环境温度
        "冷源-室外湿度": "d_w",  # 环境湿度
        "冷冻总管热量表-瞬时流量": "flow_LD",  # 冷冻水流量
        # "冷冻总管热量表-总冷热量": "real_load",  # 冷冻水流量
        "冷冻总管热量表-累计冷量": "real_load",  # 冷冻水流量
        "时间": "timestamp"
    }
    '''
    # endregion
    data = get_flow_report(id=id, start_time=start_time, end_time=end_time, rename_map=rename_map)

    data.to_csv(f'{OUTPUT_DIR}/看看数据.csv')

    data = data.rename(columns={
        't_LD_out': 't_out',#冷冻水出水温度
        't_LD_in': 't_in',#冷冻水进水温度
        'flow_LD': 'flow'#冷冻水流量
    })
        # 计算冷负荷
    midu_water = 1000 # 水的密度为1000kg/m3
    c_water = 4.186 # 水的比热容为4.186kJ/(kg·℃)
    #data['Load'] = data['flow']*midu_water*c_water*(data['t_in']-data['t_out'])/3600
    # 对负荷进行修正，考虑水温的变化
    #data['t_in_diff'] = data['t_in'].diff()
    #data['t_out_diff'] = data['t_out'].diff()
    #data['real_load'] = data['Load'] +(data['t_out_diff']- data['t_in_diff'])*midu_water*c_water*data['flow']/3600
    # 计算环境含湿量

    data["humidity_w"] = calculate_humidity_ratio(data["t_w"], data["d_w"])
    
    data.to_csv(os.path.join(OUTPUT_DIR, "load_data_origin.csv"), index=False)
    # 仅保留需要的列
    columns = ['timestamp','t_w','humidity_w','real_load']
    data = data[columns]
    # 改变列名
    data = data.rename(columns={
        't_w': 'swt',
        'humidity_w': 'swh',
        'real_load': 'real_load'
    })
    # 删除nan行
    data = data.dropna()
    # 保存到CSV
    save_path = os.path.join(OUTPUT_DIR, "load_data.csv")
    # data.to_csv(save_path, index=False)

    return data

if __name__ == "__main__":

    start_time = "2025-08-24 00:00:00"
    end_time = "2025-08-25 01:00:00"
    data = calculate_load(start_time, end_time)
    # 筛选real_load非0的数据并打印数量
    non_zero_data = data[data['real_load'] != 0]
    print(f"非零负荷数据数量: {len(non_zero_data)}")
    print(data)




    






